package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.utils.FileUploader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Autowired
    private FileUploader fileUploader;

    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
/*        //获取webapp目录
        String path = request.getSession().getServletContext().getRealPath("/");*//*
        //生成UUId文件名
        String fileName=UUID.randomUUID().toString();
        //获取文件后缀 .jpg
        String lastName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
*//*        //获取文件在服务器中的路径 /images/0ced4579-9e35-4c2a-b3ec-7391401d3a0a.jpg
        String filePath2 = bashPath+fileName+lastName;*//*
        //拼接完整的文件路径名
        String filePath = basePath +fileName+lastName;
        System.out.println(filePath);
        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在
        if(!dir.exists()){
            //目录不存在，需要创建
            dir.mkdirs();
        }
        //根据文件的路径名 创建文件对象
        File destFile = new File(filePath);
        //写入到file中(服务器中)
        file.transferTo(destFile);
        //返回文件名 0ced4579-9e35-4c2a-b3ec-7391401d3a0a
        String imgUrl = fileName+lastName;*/

        return R.success(fileUploader.upload(file));
    }

    @GetMapping("/download")
    public void downloadFile(String name, HttpServletResponse response){
        try {
            File file = new File(basePath+name);
            if (!file.exists()){
                //判断文件是否存在 不存在则 直接返回
                System.out.println("文件不存在"+file);
                return;
            }
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            ServletOutputStream outputStream=response.getOutputStream();
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = bis.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
